<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Rate 评分</title>
  </head>
  <style>
    .square {
      display: inline-block;
      width: 20px;
      height: 20px;
      border: 1px solid;
      border-radius: 50%;
    }
  </style>
  <body>
    <div>
      <span class="square"></span>
      <span class="square"></span>
      <span class="square"></span>
      <span class="square"></span>
      <span class="square"></span>
    </div>
  </body>

  <script>
    let squares = document.querySelectorAll('.square')
    squares.forEach((square, index) => {
      square.addEventListener('click', () => {
        for (let i = 0; i < squares.length; i++) {
          squares[i].style.backgroundColor = 'white'
        }
        for (let i = 0; i <= index; i++) {
          squares[i].style.backgroundColor = 'red'
        }
      })

      square.addEventListener('mouseover', () => {
        // 鼠标移入时，改变每个圆形的背景颜色
        for (let i = 0; i < squares.length; i++) {
          squares[i].style.backgroundColor = 'white' // 恢复所有圆形为白色
        }
        // 鼠标悬停的圆形及其前面的圆形变为红色
        for (let i = 0; i <= index; i++) {
          squares[i].style.backgroundColor = 'red'
        }
      })

      square.addEventListener('mouseout', () => {
        // 鼠标移出时，恢复所有圆形为白色
        for (let i = 0; i < squares.length; i++) {
          squares[i].style.backgroundColor = 'white'
        }
      })
    })
  </script>
</html>
